import React, {PropTypes} from 'react';
import {connect} from 'react-redux'

import {Divider, Dropdown, Button, Menu, Tag, Switch, Icon} from "antd";
import Condition from 'components/condition'
import newByInvoiceImg from "images/corporate-payment-report/new-by-invoice.png";
import newExpenseImg from "images/corporate-payment-report/new-expense.png";
import InvoiceOCRCheck from "containers/my-account/components/invoice-ocr-check";
import expenseService from "containers/my-account/expense.service";
import SlideFrame from 'components/slide-frame';
import baseService from "share/base.service";
import NewExpense from 'containers/my-account/new-expense'
import defaultExpenseTypeIcon from "images/expense/default-expense-type.png";
import {deepFullCopy, messages, queryCurrencyPrecision} from "share/common";
import ExpenseDetail from "../../../expense";
import CommonModal from '../../../expense/component/common-modal';
const {If, Else} = Condition;

class CreateExpenseCard extends React.Component {

  state = {
    invoiceTypeList: [],
    showOCRFlag: false,
    invoiceFp: {},
    currencyList: [{
      baseCurrency: this.props.expenseInfo.baseCurrency,
      currency: this.props.expenseInfo.currency,
      currencyName: this.props.expenseInfo.currencyCodeName,
    }],
    showExpenseFlag: false,
    costCenterItemsApportion: [],
    invoiceViewDTO: {},
    receiptList: []
  };

  componentWillMount() {
    const {invoiceTypeList} = this.state;
    const {applicantOID} = this.props;
    this.getOCRFlag();
    this.getFpByUserOID(applicantOID);
    this.getCostCenterItems();
    !invoiceTypeList.length && this.getInvoiceTypeList();
    this.setState({ invoiceViewDTO: this.props.invoiceViewDTO });
  }

  componentWillReceiveProps(nextProps) {
    if (!this.props.invoiceViewDTO && nextProps.invoiceViewDTO ||
      nextProps.invoiceViewDTO && nextProps.invoiceViewDTO.id !==
      this.props.invoiceViewDTO && this.props.invoiceViewDTO.id
    ) {
      this.setState({ invoiceViewDTO: nextProps.invoiceViewDTO })
    }
  }

  getInvoiceTypeList = () => {
    const { applicantOID } = this.props;
    return expenseService.getInvoiceTypeList(applicantOID).then(res => {
      this.setState({ invoiceTypeList: res.data.rows || [] })
    })
  };

  //获取是否开通OCR
  getOCRFlag = () => {
    const { applicantOID } = this.props;
    return expenseService.getTitleList(applicantOID).then(res => {
      this.setState({ showOCRFlag: res.data.showOCRFlag })
    })
  };

  //根据用户OID获取FP，用户不同用户操作同一页面。如财务操作用户费用页面，取员工FP
  getFpByUserOID(applicantOID) {
    baseService.getFpByUserOID(applicantOID).then(res => {
      this.setState({ invoiceFp: res.data })
    });
  }

  getCostCenterItems = () => {
    const { expenseInfo: { custFormValues } } = this.props;
    let costCenterItemsApportion = [];
    //查询是否多币种、初始化成本中心项
    custFormValues && custFormValues.map(field => {
      if (field.messageKey === 'select_cost_center') {
        if (JSON.parse(field.fieldConstraint || '{}').isApportionItem) { //参与分摊
          costCenterItemsApportion.push({
            fieldName: field.fieldName,
            costCenterOID: JSON.parse(field.dataSource || '{}').costCenterOID,
            costCenterItemName: field.showValue,
            name: field.showValue,
            costCenterItemOID: field.value,
            required: field.required
          })
        }
      }
      if (field.messageKey === 'select_department') {
        if (JSON.parse(field.fieldConstraint || '{}').isApportionItem) { //参与分摊
          costCenterItemsApportion.push({
            fieldName: field.fieldName,
            costCenterOID: '00000000-0000-0000-0000-000000000000',
            costCenterItemName: field.showValue,
            name: field.showValue,
            costCenterItemOID: field.value,
            required: field.required
          })
        }
      }
    });
    this.setState({ costCenterItemsApportion });
  };

  //渲染添加发票方式的选项
  renderInvoiceAddMenu = showOCRFlag => {
    const { options: { receiptSourceOpt } } = this.props;
    const { invoiceTypeList } = this.state;
    let handleMenuItemClick = (e) => {
      if (!['image', 'pdf', 'ofd'].includes(e.key)) {
        this.openNewExpense('invoice', { receiptOperateScene: 1, invoiceTypeNo: e.key })
      }
    };
    return (
      <Menu onClick={handleMenuItemClick}>
        {showOCRFlag && ['image', 'pdf', 'ofd'].map(type => (
          <Menu.Item key={type} style={{ padding: 0 }}>
            {this.renderInvoiceAddMenuItem(type)}
          </Menu.Item>
        ))}
        {receiptSourceOpt.handInvoice && (
          <Menu.SubMenu
            title={messages('finance-9.key37')/*手动录入*/}
            className="button-add-invoice-menu-subItem"
          >
            {invoiceTypeList.map(item => (
              <Menu.Item key={item.value}>
                {item.messageKey}{item.remark ? `(${item.remark})` : ''}
              </Menu.Item>
            ))}
          </Menu.SubMenu>
        )}
      </Menu>
    )
  };

  renderInvoiceAddMenuItem = (type) => {
    const { applicantOID, tab, entry } = this.props;
    const { isAuditEditable } = this.context;
    let checkOCRSuccess = (OCRList) => {
      this.openNewExpense('invoiceOCR', { OCRList, receiptOperateScene: 1 })
    };
    let invoiceEdit = (receipt) => {
      this.openNewExpense('invoice', { receipt, receiptOperateScene: 3 });
    };
    let importSuccessInvoice = (receipt) => {
      this.openNewExpense('expenseType', { receiptList: [receipt], receiptOperateScene: 1 })
    };
    let toEditDisabledPage = (receipt) => {
      this.openNewExpense('invoiceDisabledEdit', { receipt });
    };
    return (
      <InvoiceOCRCheck
        type={type}
        expenseType={{}}
        nowExpense={{}}
        createType={isAuditEditable ? 2 : 1} //创建类型：1.用户操作类型 2.财务操作类型
        checkSuccess={checkOCRSuccess}
        invoiceEdit={invoiceEdit}
        importSuccessInvoice={importSuccessInvoice}
        toEditDisabledPage={toEditDisabledPage}
        expenseReportOID={''}
        applicantOID={applicantOID}
        ownerOID={applicantOID}
        currentTab={tab || ''}
      />
    )
  };

  operateReceiptCallback = () => {
    const { receiptOperateScene } = this.state;
    this.getDefaultValueByInvoice();
  };

  //receiptOperateScene 发票操作场景：1.发票创建费用；2.费用新增发票；3.费用编辑发票
  openNewExpense = (key, extraParams) => {
    const { invoiceViewDTO, costCenterItemsApportion, expenseType, receiptList, attachments } = this.state;
    const { user, expenseInfo } = this.props;
    const { jobInfo, entry } = this.context;
    let nowExpenseType = expenseType || (invoiceViewDTO ? {
      name: invoiceViewDTO.expenseTypeName,
      expenseTypeOID: invoiceViewDTO.expenseTypeOID,
      id: invoiceViewDTO.expenseTypeId,
      iconName: invoiceViewDTO.expenseTypeIconName,
      iconURL: invoiceViewDTO.expenseTypeIconURL,
      messageKey: invoiceViewDTO.expenseTypeKey,
      fields: invoiceViewDTO.data
    } : {});

    SlideFrame.open({
      title: invoiceViewDTO ? messages('finance-9.key38')/*编辑费用*/ : messages('finance-9.key39')/*新建费用*/,
      content: NewExpense,
      width: 800,
      hasFooter: false,
      // hasMask: false,
      afterClose: this.onGetExpenseDetail,
      params: {
        user,
        slideFrameShowFlag: true,
        hasInit: false,
        isFinance: entry === 'audit',
        corporateFlag: true,
        nowExpense: deepFullCopy(invoiceViewDTO),
        expenseSource: key,
        // receiptOperateScene: 2,
        invoiceTypeNo: key === 'invoice' ? extraParams.invoiceTypeNo : null,
        expenseType: nowExpenseType,
        expenseReport: expenseInfo,
        costCenterItemsApportion: costCenterItemsApportion,
        jobInfo: jobInfo,
        receiptList,
        attachments,
        ...extraParams,
      },
    }, this);
  };

  onGetExpenseDetail = params => {
    if(params && params.extraParams) {
      this.setState({
        invoiceViewDTO: params.extraParams.expense,
        expenseType: params.extraParams.expenseType,
        receiptList:  params.extraParams.receiptList || [],
        attachments: params.extraParams.attachments || [],
      });
      this.props.onGetExpenseDetail(params.extraParams.expense);
    }
  };

  static contextTypes = {
    isAuditEditable: PropTypes.bool,
    isWaitForAudit: PropTypes.bool,
    jobInfo: PropTypes.object,
    info: PropTypes.object,
    entry: PropTypes.string,
    expenseReportInvoices: PropTypes.array
  };

  handleClose = (params = {}) => {
    const { isEdit, isSwitchOld } = params;
    if (isSwitchOld || isEdit) {
      isSwitchOld && window.localStorage.setItem('hly.auto.check', 'true');
      this.openNewExpense('', { readOnly: true });
    }
  };

  handleSwitchNew = () => {
    window.localStorage.setItem('hly.auto.check', 'false');
    const { isAuditEditable, isWaitForAudit, jobInfo, info: expenseReport } = this.context;
    const { invoiceViewDTO } = this.state;
    CommonModal.open(
      {
        jobInfo,
        auditTab: 'all',
        nowExpense: invoiceViewDTO,
        expenseReport,
        isWaitForAudit,
        isAuditEditable,
        expenseReportInvoices: [invoiceViewDTO],
        handleClose: this.handleClose,
        children: <ExpenseDetail/>
      }, this);
  };

  render() {
    const { showOCRFlag, invoiceViewDTO } = this.state;
    const { editable, expenseInfo } = this.props;
    return (
      <div>
        {!invoiceViewDTO ? (
        <div className='create-expense-card'>
          <Dropdown
            trigger="click"
            getPopupContainer={() => document.getElementsByClassName('create-expense-card')[0]}
            overlay={this.renderInvoiceAddMenu(showOCRFlag)}
          >
            <div className='new-by-invoice'>
              <img src={newByInvoiceImg} className='icon'/>
              <div>{messages('finance-9.key40')/*从发票生成费用*/}</div>
            </div>
          </Dropdown>
          <Divider type="vertical" style={{height: '100%'}}/>
          <div className='new-expense-direct' onClick={() => this.openNewExpense('expenseType', { receiptOperateScene: 2 })}>
            <img src={newExpenseImg} className='icon'/>
            <div>{messages('finance-9.key41')/*直接新建费用*/}</div>
          </div>
        </div>
        ) : (
        <div className='expense-card'>
          {editable ?
            <a className='expense-card-edit' onClick={() => this.openNewExpense('')}>{messages('common.edit')/*编辑*/}</a> :
            <a className='expense-card-edit' onClick={() => this.handleSwitchNew()}>{messages('common.view')/*查看*/}</a>
          }
          <img src={invoiceViewDTO.expenseTypeIconURL || defaultExpenseTypeIcon} className='expense-card-icon' />
          <div className='expense-card-name'>{invoiceViewDTO.expenseTypeName}</div>
          <div className='expense-card-info'>
            {messages('finance-9.key4')/*到票金额*/}：
            {invoiceViewDTO.currencyCode + ' ' + Number(invoiceViewDTO.amount || 0).toFixed(queryCurrencyPrecision(expenseInfo.currencyCode))}
          </div>
          {invoiceViewDTO.comment && <div className='expense-card-info'>
            {messages('common.remark')/*备注*/}：
            {invoiceViewDTO.comment || '-'}
          </div>}
        </div>
        )}
      </div>
    )
  }
}

CreateExpenseCard.propsType = {

};

CreateExpenseCard.defaultProps = {

};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    company: state.login.company,
    user: state.login.user,
    authPolicyAll: state.main.authPolicyAll,
    options: state.login.options,
    profile: state.login.profile,
  }
}

export default connect(mapStateToProps)(CreateExpenseCard)
